 <template>
  <div class="page">
    <s-header :name="'联审办理'" :back="'/government/joint-review'"></s-header>
    <div class="card-box">
      <div class="card-item">
        <div class="card-header">
          <div class="header-title">建房申请单号：{{ buildDataForm.applyOrderNo }}</div>
        </div>
        <van-divider />
        <div class="card-body card-body-nop">
          <van-cell title="申请人" :value="buildDataForm.applyName" />
          <van-cell title="申请时间" :value="buildDataForm.applyTime" />
          <van-cell title="联系电话" :value="buildDataForm.applyPhone" />
          <van-cell title="申请理由" :value="buildDataForm.applyReasonsDesc" />
          <van-cell title="建房类型" :value="buildDataForm.buildTypeName" />
          <van-cell title="家庭住址" :value="buildDataForm.applyHouseAddress" />
        </div>
      </div>

      <div class="card-item">
        <div class="card-header">
          <div class="item-head">
            <div class="title">各部门审查结果</div>
          </div>
        </div>
        <van-divider />
        <div class="card-body">
          <div class="item-body">
            <div class="dept-result">
              <van-row class="dept-head">
                <van-col span="6">
                  <div class="cell">审查机构</div>
                </van-col>
                <van-col span="6">
                  <div class="cell">反馈状态</div>
                </van-col>
                <van-col span="6">
                  <div class="cell">审查结果</div>
                </van-col>
                <van-col span="6">
                  <div class="cell">操作</div>
                </van-col>
              </van-row>
              <van-row v-for="(item, index) in deptListList" :key="index" class="table-cell">
                <van-col span="6">
                  <div class="cell link-text">{{ item.reviewDeptDesc }}</div>
                </van-col>
                <van-col span="6">
                  <div class="cell">
                    <div :class="`btn-status ${item.status == 1 ? 'status-success' : 'status-danger'}`">
                      {{ item.status == 1 ? '已反馈' : '未反馈' }}
                    </div>
                  </div>
                </van-col>
                <van-col span="6">
                  <div class="cell" v-show="item.reviewResult != '0'">{{ item.reviewResult == '1' ? '合格' : '不合格' }}</div>
                </van-col>
                <van-col span="6">
                  <div class="cell">
                    <span class="link-text" v-show="item.status == 1" @click="handleToDetail(item)">查看详情</span>
                  </div>
                </van-col>
              </van-row>
            </div>
          </div>
        </div>
      </div>

      <van-form ref="dataFormRef">
        <div class="card-item">
          <div class="card-header">
            <div class="header-title title-required">审批结果</div>
          </div>
          <van-divider />
          <div class="card-body">
            <van-radio-group v-model="dataForm.reviewResult" :rules="dataRule.reviewResult" direction="horizontal">
              <van-radio name="12">同意发证</van-radio>
              <van-radio name="13">退回至申请人</van-radio>
              <van-radio name="99">挂起</van-radio>
            </van-radio-group>
          </div>
        </div>

        <div class="card-item">
          <div class="card-header">
            <div class="header-title title-required">办理意见</div>
          </div>
          <van-divider />
          <div class="card-body">
            <van-field
              v-model="dataForm.handleOpinions"
              :rules="dataRule.handleOpinions"
              class="noPadding"
              label=""
              rows="3"
              autosize
              type="textarea"
              placeholder="请输入办理意见"
            />
          </div>
        </div>
      </van-form>

      <div class="card-item">
        <div class="card-header">
          <div class="item-head">
            <div class="title title-required">乡村建设规划许可证（签章版）</div>
          </div>
        </div>
        <van-divider />
        <div class="card-body">
          <image-upload v-model:value="licenceFile" fileType="006" @uploadBack="uploadBack"></image-upload>
        </div>
      </div>
      <div class="card-item">
        <div class="card-header">
          <div class="item-head">
            <div class="title title-required">农村宅基地批准书（签章版）</div>
          </div>
        </div>
        <van-divider />
        <div class="card-body">
          <image-upload v-model:value="ratifyFile" fileType="007" @uploadBack="uploadBack"></image-upload>
        </div>
      </div>
      <div class="card-item last-item">
        <div class="card-header">
          <div class="item-head">
            <div class="title">其他材料</div>
          </div>
        </div>
        <van-divider />
        <div class="card-body">
          <image-upload v-model:value="otherFileList" fileType="008" @uploadBack="uploadBack"></image-upload>
        </div>
      </div>
    </div>

    <div class="btn-group">
      <van-button type="button" class="cus-btn btn-default" @click="handleSave">保存</van-button>
      <van-button :loading="isCommit" type="button" class="cus-btn btn-primary" @click="handleTransact">提交</van-button>
    </div>
  </div>
</template>

<script>
import { reactive, toRefs, ref, onMounted, getCurrentInstance, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { Toast } from 'vant'
import sHeader from '@/components/SimpleHeader'
import ImageUpload from '@/components/ImageUpload'
import { jointReviewDetail, saveJointReview } from '@/service/govern'
export default {
  components: { sHeader, ImageUpload },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const store = useStore()
    const dataFormRef = ref(null)
    const state = reactive({
      isCommit: false,
      dataForm: {
        reviewResult: '12',
        handleOpinions: '',
      },
      reviewId: '',
      applyBaseId: '',
      buildDataForm: {
        applyOrderNo: '',
        applyName: '',
        applyTime: '',
        applyPhone: '',
        applyReasonsDesc: '',
        buildTypeName: '',
        applyHouseAddress: '',
      },
      deptListList: [], // 各部门审查结果
      licenceFile: [],
      ratifyFile: [],
      otherFileList: [],
      attachInfoList: [],
      dataRule: {
        handleOpinions: [{ required: true, message: '请输入办理意见', trigger: 'onBlur' }],
        reviewResult: [{ required: true, message: '请选择审批结果', trigger: 'onChange' }],
      },
    })

    // 全局属性
    const { listAssign } = getCurrentInstance().appContext.config.globalProperties
    store.dispatch('getFileServerPrefix')

    onMounted(async () => {
      const { id } = route.params
      if (id && id != 'undefined') {
        jointReviewDetail(id).then((res) => {
          const data = res.data
          state.deptListList = data.deptListList || []

          listAssign(state.buildDataForm, data.buildApplyBase)
          if (data.jointReviewOpinions) listAssign(state.dataForm, data.jointReviewOpinions)

          state.reviewId = data.jointReviewOpinions.id

          let licenceFile = []
          let ratifyFile = []
          let otherFileList = []
          if (data.attachInfoList) {
            data.attachInfoList.forEach((item) => {
              item.filePath = item.url
              item.url = fileServerPrefix.value + item.url
              switch (item.type) {
                case '006':
                  licenceFile.push(item)
                  break
                case '007':
                  ratifyFile.push(item)
                  break
                case '008':
                  otherFileList.push(item)
                  break
                default:
                  break
              }
            })
          }
          state.licenceFile = licenceFile
          state.ratifyFile = ratifyFile
          state.otherFileList = otherFileList
          // state.attachInfoList = data.attachInfoList || []
        })
      } else {
        router.push({ path: `/government/joint-review` })
      }
    })

    const handleToEdit = (id, type) => {
      router.push({
        path: '/government/review-item',
        query: { id: id, type: type, pageId: route.params.id, reviewModule: '5', pagePath: '/government/joint-review/transact' },
      })
    }

    // 文件上传后回调
    const uploadBack = (fileList, type) => {
      switch (type) {
        case '006':
          state.licenceFile = fileList
          break
        case '007':
          state.ratifyFile = fileList
          break
        case '008':
          state.otherFileList = fileList
          break
        default:
          break
      }
    }

    // 部门审查结果详情
    const handleToDetail = (item) => {
      sendRequest('0').then(() => {
        router.push({
          path: `/government/joint-review/feedback`,
          query: { applyBaseId: item.applyBaseId, reviewDept: item.reviewDept, pageId: route.params.id },
        })
      })
    }

    const handleSave = () => {
      sendRequest('0').then(() => {
        Toast.success(`保存成功`)
        setTimeout(() => {
          router.push({ path: `/government/joint-review` })
        }, 500)
      })
    }

    const handleTransact = () => {
      dataFormRef.value.validate().then(() => {
        if (state.licenceFile.length === 0) {
          Toast.fail(`请上传乡村建设规划许可证（签章版）`)
          return
        }
        if (state.ratifyFile.length === 0) {
          Toast.fail(`请上传农村宅基地批准书（签章版）`)
          return
        }
        sendRequest('1').then(() => {
          Toast.success(`提交成功`)
          setTimeout(() => {
            router.push({ path: `/government/joint-review` })
          }, 500)
        })
      })
    }

    const sendRequest = (isSubmit) => {
      return new Promise((resolve, reject) => {
        state.isCommit = true

        let licenceFile = JSON.parse(JSON.stringify(state.licenceFile))
        let ratifyFile = JSON.parse(JSON.stringify(state.ratifyFile))
        let otherFileList = JSON.parse(JSON.stringify(state.otherFileList))
        licenceFile.forEach((item, index) => {
          item.sort = index
          item.url = item.filePath ? item.filePath : item.url
        })
        ratifyFile.forEach((item, index) => {
          item.sort = index
          item.url = item.filePath ? item.filePath : item.url
        })
        otherFileList.forEach((item, index) => {
          item.sort = index
          item.url = item.filePath ? item.filePath : item.url
        })

        let params = {
          attachInfoList: [...licenceFile, ...ratifyFile, ...otherFileList],
          jointReviewOpinions: {
            applyBaseId: route.params.id,
            id: state.reviewId,
            isSubmit: isSubmit,
            handleOpinions: state.dataForm.handleOpinions,
            reviewResult: state.dataForm.reviewResult,
          },
        }

        saveJointReview(params)
          .then(() => {
            state.isCommit = false
            resolve(true)
          })
          .catch((err) => {
            state.isCommit = false
            reject(err)
          })
      })
    }

    const fileServerPrefix = computed(() => {
      return store.state.fileServerPrefix
    })

    return {
      dataFormRef,
      fileServerPrefix,
      ...toRefs(state),
      handleTransact,
      handleSave,
      handleToEdit,
      handleToDetail,
      uploadBack,
    }
  },
}
</script>

<style lang="less" scoped>
@import '@/common/style/mixin';
.page {
  color: #2e3f6a;
  font-weight: 400;
  .card-box {
    margin-top: 10px;
    .van-divider {
      margin: 10px 0 0;
    }
    .card-header {
      font-size: 15px;
      .item-head {
        .fj();
        .text-add {
          font-weight: 400;
          color: #3487f6;
        }
        .text-desc {
          font-size: 13px;
          font-weight: 400;
          color: #9297ae;
        }
      }
      .title-required::before {
        margin-right: 5px;
        color: var(--van-field-required-mark-color);
        content: '*';
      }
    }
    .card-body {
      padding-bottom: 10px;
      .person {
        margin-bottom: 10px;
        padding-bottom: 10px;
      }
    }
    .last-item {
      margin-bottom: 0;
    }
  }
  .btn-group {
    padding: 30px 0 20px;
    .cus-btn {
      width: 167px;
    }
  }
  .dept-result {
    font-size: 13px;
    color: #2e3f6a;
    font-weight: 400;
    text-align: center;
    .cell {
      padding: 10px 0;
      height: 100%;
      min-width: 0;
      box-sizing: border-box;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .dept-head {
      background: #f4f5f9;
      border-radius: 3px;
    }
    .table-cell {
      border-bottom: 1px solid #dee1eb;
      .link-text {
        color: #3487f6;
        line-height: 18px;
      }
      .btn-status {
        padding: 5px 10px;
        border-radius: 3px;
      }
      .status-success {
        background: #e8f7e0;
        color: #5eb02d;
      }
      .status-danger {
        color: #df3838;
        background: #ffe9e9;
      }
    }
  }
}
</style>
